<?php

class ControllerSalePurchaseOrder extends Controller {
  private $error = array();

  public function vendor(){
    $this->load->model('sale/purchase_order');
    $json = array();
    $filter_name = I('get.filter_name');
    if(!$filter_name){
      $filter_name='';
    }
    $vendors = $this->model_sale_purchase_order->getVendors($filter_name);
    if($vendors){
      $json = $vendors;
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function product(){
    $json = array();

    if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
      $this->load->model('catalog/product');
      $this->load->model('catalog/option');
      $this->load->model('sale/purchase_order');

      if (isset($this->request->get['filter_name'])) { //复合查询
        $where['pd.name'] = array('like', '%'.trim($this->request->get['filter_name']).'%');
		$where['pov.product_code'] = array('like', '%'.trim($this->request->get['filter_name']).'%');
		$where['product.sku'] = array('like', '%'.trim($this->request->get['filter_name']).'%');
		$where['_logic'] = 'or';
		$filter['_complex'] = $where;
      }
      if(!empty($this->request->get['filter_vendor'])){
        $filter['vendor.vendor'] = $this->request->get['filter_vendor'];
      }
      $results = $this->model_sale_purchase_order->getProducts($filter);

      foreach ($results as $result) {
        $option_data = array();

        $product_options = $this->model_catalog_product->getProductOptions($result['product_id']);

        foreach ($product_options as $product_option) {
          $option_info = $this->model_catalog_option->getOption($product_option['option_id']);

          if ($option_info) {
            $product_option_value_data = array();

            foreach ($product_option['product_option_value'] as $product_option_value) {
              $option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

              if ($option_value_info) {
                $product_option_value_data[] = array(
                  'product_option_value_id' => $product_option_value['product_option_value_id'],
				          'product_code' => $product_option_value['product_code'],
                  'option_value_id'         => $product_option_value['option_value_id'],
                  'name'                    => $option_value_info['name'],
                  'price'                   => (float)$product_option_value['price'],
                  'price_prefix'            => $product_option_value['price_prefix']
                );
              }
            }

            $option_data[] = array(
              'product_option_id'    => $product_option['product_option_id'],
              'product_option_value' => $product_option_value_data,
              'option_id'            => $product_option['option_id'],
              'name'                 => $option_info['name'],
              'type'                 => $option_info['type'],
              'value'                => $product_option['value'],
              'required'             => $product_option['required']
            );
          }
        }

        $json[] = array(
          'product_id' => $result['product_id'],
          'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
          'model'      => $result['model'],
          'cost'          => $result['product_cost'],
          'sku'         =>$result['sku'],
          'option'     => $option_data,
          'option_name'     => $option_value_info['name'],
          'option_id'     => $product_option['option_id'],
          'price'      => $result['price'],
          'packing_no' => $result['packing_no'],
          'product_code' => $result['vproduct_code'],
          'clearance' => $result['clearance'],
        );
      }
    }
    //var_dump($json);die();
    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function export(){
    $po_id = I('get.po_id');
    if(!$po_id){
      $po_id = 0;
    }
    $this->load->model('sale/purchase_order');
    $po = $this->model_sale_purchase_order->getPo($po_id);

    $data['po'] = $po;
    if(!$po){
      $this->load->language('error/not_found');

      $this->document->setTitle($this->language->get('heading_title'));

      $data['heading_title'] = $this->language->get('heading_title');

      $data['text_not_found'] = $this->language->get('text_not_found');

      $data['breadcrumbs'] = array();

      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
      );


      $data['footer'] = $this->load->controller('common/footer');

      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
    }
    $po_products = $this->model_sale_purchase_order->getPoProducts($po_id);
    $data['po_products'] = $po_products;

    $this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/po_tpl.xls");
    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("Bai Huo Zhan PO")
               ->setSubject("Bai Huo Zhan PO")
               ->setDescription("Bai Huo Zhan PO")
               ->setKeywords("Bai Huo Zhan, Think-tec")
               ->setCategory("Think-tec");
    // $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->setCellValue('B2', $po['id']);
    $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objActSheet->setCellValue('F2', date('Y-m-d H:i',time()));
    $objActSheet->setCellValue('B3', $po['vendor_id']);
    $objActSheet->setCellValue('B4', $po['vendor']['vendor_name']);
    $objActSheet->setCellValue('F3', $po['vendor']['firstname']);
    $objActSheet->setCellValue('F4', $po['vendor']['telephone']);
    $objActSheet->setCellValue('B5', $po['logcenter_info']['logcenter_name']);
    $objActSheet->setCellValue('D5', $po['logcenter_info']['firstname']);
    $objActSheet->setCellValue('F5', $po['logcenter_info']['telephone']);
    $objActSheet->setCellValue('B6', $po['included_order_ids']);
    $row_num = 8;
    $styleBorderOutline = array(
      'borders' => array(
        'outline' => array(
          'style' => PHPExcel_Style_Border::BORDER_THIN,
        ),
      ),
    );
    $objPHPExcel->getActiveSheet()->insertNewRowBefore(9, count($po_products));
    $count = 0;
    foreach ($po_products as $key => $po_product) {
      $row_num++;
      $objActSheet->setCellValue('A'.$row_num, $row_num-8);
      $objActSheet->setCellValue('B'.$row_num, $po_product['name'].' '.$po_product['option_name']);
      $objActSheet->setCellValueExplicit('C'.$row_num, $po_product['sku'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValue('D'.$row_num, $po_product['qty']);
      $objActSheet->setCellValue('E'.$row_num, $po_product['unit_price']);
      $objActSheet->setCellValue('F'.$row_num, $po_product['price']);
      $objActSheet->setCellValue('G'.$row_num, $po_product['comment']);

      $count += $po_product['qty'];

      $objPHPExcel->getActiveSheet()->getStyle('A'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('C'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('D'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('E'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('F'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('G'.$row_num)->applyFromArray($styleBorderOutline);
    }
    $row_num++;

    $objActSheet->setCellValue('D'.$row_num, $count);
    $objActSheet->setCellValue('F'.$row_num, $po['total']);
    $row_num++;
    $objActSheet->setCellValue('F'.$row_num, date('Y-m-d', strtotime($po['deliver_time'])));

    $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(12);

    $objActSheet->setTitle('采购单');


    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output');
    exit;
  }

  public function exportSimple(){
    $po_id = I('get.po_id');
    if(!$po_id){
      $po_id = 0;
    }
    $this->load->model('sale/purchase_order');
    $po = $this->model_sale_purchase_order->getPo($po_id);

    $data['po'] = $po;
    if(!$po){
      $this->load->language('error/not_found');

      $this->document->setTitle($this->language->get('heading_title'));

      $data['heading_title'] = $this->language->get('heading_title');

      $data['text_not_found'] = $this->language->get('text_not_found');

      $data['breadcrumbs'] = array();

      $data['breadcrumbs'][] = array(
        'text' => $this->language->get('heading_title'),
        'href' => $this->url->link('error/not_found', 'token=' . $this->session->data['token'], 'SSL')
      );


      $data['footer'] = $this->load->controller('common/footer');

      $this->response->setOutput($this->load->view('error/not_found.tpl', $data));
    }
    $po_products = $this->model_sale_purchase_order->getPoProducts($po_id);
    $data['po_products'] = $po_products;

    $this->load->library('PHPExcel/PHPExcel');
    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $objPHPExcel = $objReader->load(DIR_SYSTEM . "template/po_tpl.xls");
    $objPHPExcel->getProperties()->setCreator("Think-tec")
               ->setLastModifiedBy("Think-tec")
               ->setTitle("Bai Huo Zhan PO")
               ->setSubject("Bai Huo Zhan PO")
               ->setDescription("Bai Huo Zhan PO")
               ->setKeywords("Bai Huo Zhan, Think-tec")
               ->setCategory("Think-tec");
    // $objPHPExcel->setActiveSheetIndex(0);
    $objActSheet = $objPHPExcel->getActiveSheet();
    $objActSheet->setCellValue('B2', $po['id']);
    $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
    $objActSheet->setCellValue('F2', date('Y-m-d H:i',time()));
    $objActSheet->setCellValue('B3', $po['vendor_id']);
    $objActSheet->setCellValue('B4', $po['vendor']['vendor_name']);
    $objActSheet->setCellValue('F3', $po['vendor']['firstname']);
    $objActSheet->setCellValue('F4', $po['vendor']['telephone']);
    $objActSheet->setCellValue('B5', $po['logcenter_info']['logcenter_name']);
    $objActSheet->setCellValue('D5', $po['logcenter_info']['firstname']);
    $objActSheet->setCellValue('F5', $po['logcenter_info']['telephone']);
    $objActSheet->setCellValue('B6', $po['included_order_ids']);
    $objActSheet->setCellValue('E8', '发货数量');
    $objActSheet->setCellValue('F8', ' ');
    $row_num = 8;
    $styleBorderOutline = array(
      'borders' => array(
        'outline' => array(
          'style' => PHPExcel_Style_Border::BORDER_THIN,
        ),
      ),
    );
    $objPHPExcel->getActiveSheet()->insertNewRowBefore(9, count($po_products));
    $count = 0;
    foreach ($po_products as $key => $po_product) {
      $row_num++;
      $objActSheet->setCellValue('A'.$row_num, $row_num-8);
      $objActSheet->setCellValue('B'.$row_num, $po_product['name'].' '.$po_product['option_name']);
      $objActSheet->setCellValueExplicit('C'.$row_num, $po_product['sku'],PHPExcel_Cell_DataType::TYPE_STRING);
      $objActSheet->setCellValue('D'.$row_num, $po_product['qty']);
      // $objActSheet->setCellValue('E'.$row_num, $po_product['unit_price']);
      // $objActSheet->setCellValue('F'.$row_num, $po_product['price']);
      $objActSheet->setCellValue('G'.$row_num, $po_product['comment']);

      $count += $po_product['qty'];

      $objPHPExcel->getActiveSheet()->getStyle('A'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('B'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('C'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('D'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('E'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('F'.$row_num)->applyFromArray($styleBorderOutline);
      $objPHPExcel->getActiveSheet()->getStyle('G'.$row_num)->applyFromArray($styleBorderOutline);
    }
    $row_num++;

    $objActSheet->setCellValue('D'.$row_num, $count);
    //$objActSheet->setCellValue('F'.$row_num, $po['total']);
    $row_num++;
    $objActSheet->setCellValue('F'.$row_num, date('Y-m-d', strtotime($po['deliver_time'])));

    $objPHPExcel->getActiveSheet()->getStyle('A7:G'.$row_num)->getFont()->setSize(12);

    $objActSheet->setTitle('采购单');


    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    ob_end_clean();
    // Redirect output to a client’s web browser (Excel2007)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="PO_BHZ_'.date('Y-m-d-H-i',time()).'.xlsx"');
    header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    header('Cache-Control: max-age=1');
    // If you're serving to IE over SSL, then the following may be needed
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objWriter->save('php://output');
    exit;
  }

  public function index() {

    $this->document->setTitle('采购单');

    $this->load->model('sale/purchase_order');

    $this->getList();
  }

  public function add() {
    if($this->user->getLPLevel() != 1) {
      //return;
    }

    $this->document->setTitle('新增采购单');
    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/purchase_order');

    $this->form();
  }

  public function edit(){

    $this->document->setTitle('查看采购单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/purchase_order');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $po = $this->model_sale_purchase_order->getPo($id);
    $data['po'] = $po;
    $po_products = $this->model_sale_purchase_order->getPoProducts($id);
    $data['po_products'] = $po_products;
    $po_histories = $this->model_sale_purchase_order->getPoHistory($id);
    $stock_in = $this->model_sale_purchase_order->getStockin($id);
    $data['ro_stockin'] = $stock_in;
    $data['po_histories'] = $po_histories;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    if($po['status'] == 6) {
      echo '已经审核完成采购单不能继续编辑';
      die();
    }

    $this->response->setOutput($this->load->view('sale/purchase_order_edit.tpl', $data));
  }


  public function editnew(){

    $this->document->setTitle('查看采购单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_editpo.js');

    $this->load->model('sale/purchase_order');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }

    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $po = $this->model_sale_purchase_order->getPo($id);
     $data['po'] = $po;
      // var_dump($data['po']);
    $po_products = $this->model_sale_purchase_order->getPoProducts($id);
    $data['po_products'] = $po_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    if($po['status'] == 6) {
      echo '已经审核完成采购单不能继续编辑';
      die();
    }

    $this->response->setOutput($this->load->view('sale/purchase_order_editnew.tpl', $data));
  }


  public function view(){

    $this->document->setTitle('查看采购单');

    $this->document->addScript('view/javascript/angular.js');
    $this->document->addScript('view/javascript/bhz_ctl.js');

    $this->load->model('sale/purchase_order');
    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }


    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $po = $this->model_sale_purchase_order->getPo($id);
    $data['po'] = $po;
    $po_products = $this->model_sale_purchase_order->getPoProducts($id);
    // var_dump($po_products);
    $data['po_products'] = $po_products;
    $po_histories = $this->model_sale_purchase_order->getPoHistory($id);
    $data['po_histories'] = $po_histories;
    $data['included_orders'] = explode(',', $po['included_order_ids']);

    $can_add_po = $this->user->getLPLevel() == 1;
    $can_add_po = 1;
    if($po['status']==7 && $can_add_po) {
      $data['need_allow'] = true;
    }

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/purchase_order_view.tpl', $data));
  }

  public function save(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');

      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      if(!$data['products']||!$data['vendor']){
        $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
      }
      else{
        //过滤included_order_ids
        $data['included_order_ids'] = str_replace(array("，"," "), array(",",""), $data['included_order_ids']);
        $po_id = $this->model_sale_purchase_order->addPo($data, $this->user->getId());
      }
      $this->response->setOutput(json_encode(array('success'=>true, 'info'=>$po_id)));
      return;
    }
  }

  public function confirm_po(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      if(!$data['products']){
        $this->response->setOutput(json_encode(array('success'=>false, 'info'=>'数据不完整')));
      }
      else{
        //过滤included_order_ids
        $data['included_order_ids'] = str_replace(array("，"," "), array(",",""), $data['included_order_ids']);
        // var_dump($data);
        $po_id = $this->model_sale_purchase_order->updatePo($data, $this->user->getId());
      }
      $this->response->setOutput(json_encode(array('success'=>true)));
      return;
    }
  }

  public function saveStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);
      if(!$data['products']){
        $this->response->setOutput(json_encode(array('error'=>'数据不完整')));
        return;
      }

      $to_save_stock = array();
      foreach ($data['products'] as $po_product) {
        $to_save_stock[$po_product['po_product_id']] = $po_product['stock'];
      }
      $to_save_stock2 = array();

      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }

      $po = $this->model_sale_purchase_order->getPo($id);
      //判断po状态，如果是已经结算或者已经关闭，则不允许修改po数量
      if($po['status'] == 5 || $po['status'] == 9) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改已结算和已关闭采购单')));
        return;
      }

      $po_products = $this->model_sale_purchase_order->getPoProducts($id);

      //检查stock数量是否在-delivered_qty之间~qty-delivered_qty之间
      $stock_error = array();
      foreach ($po_products as $po_p) {
        if(isset($to_save_stock[$po_p['id']])) {
          if($to_save_stock[$po_p['id']] > $po_p['qty']-$po_p['delivered_qty'] || $to_save_stock[$po_p['id']] < -$po_p['delivered_qty']) {
            $stock_error[$po_p['id']] = '数值需要为0' . '~' . ($po_p['qty']-$po_p['delivered_qty']) . '之间';
          }
          $to_save_stock2[$po_p['id']] = $to_save_stock[$po_p['id']];
        }
      }
      if(!empty($stock_error)) {
        $this->response->setOutput(json_encode(array('error'=>'入库数量不对', 'data'=>$stock_error)));
        return;
      }

      $this->model_sale_purchase_order->setStock($id, $to_save_stock2);
      $event_data['po_id'] = $id;
      $event_data['to_save_stock'] = $to_save_stock;

      $this->event->trigger('po.product.addstock', $event_data);

      //添加po入库操作记录
      $this->load->model('catalog/logcenter');
      //$logcenter_info = $this->model_catalog_logcenter->getLogcenterByUserId($this->user->getId());
      $comment = $this->model_catalog_logcenter->genPutInStockMsg($to_save_stock2);

      $stockid = $this->model_sale_purchase_order->addStock($id, $to_save_stock2);

      if ($stockid) {
          $comment2 = $this->model_catalog_logcenter->genPutInStockInMsg($stockid,$to_save_stock2);
      }
      //$this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), $logcenter_info['logcenter_name'], $comment,$comment2);
      $this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), $this->user->getUserName(), $comment,$comment2);
      $comments = "新建入库单" ;
      //$this->model_sale_purchase_order->addStHistory($stockid, $this->user->getId(),$logcenter_info['logcenter_name'],$comments);
      $this->model_sale_purchase_order->addStHistory($stockid, $this->user->getId(),$this->user->getUserName(),$comments);
      //判断库存是否全部匹配，如果是的话，就置为全部收货，否则置为部分收货
      $po_products = $this->model_sale_purchase_order->getPoProducts($id);
      $delivered_qty_total = 0;
      $fully_delivered = true;
      $po_status = 0;
      foreach ($po_products as $po_p) {
        $delivered_qty_total += $po_p['delivered_qty'];
        if($po_p['qty'] != $po_p['delivered_qty']) {
          $fully_delivered = false;
        }
      }
      if($fully_delivered) {
        $po_status = 4;
      } elseif($delivered_qty_total!=0) {
        $po_status = 3;
      }
      if($po_status != 0) {
        $this->model_sale_purchase_order->changePoStatus($id, $po_status);
        //全部入库记录更新
        if($po_status == 4) {
          $this->load->model('catalog/logcenter');
          //$logcenter_info = $this->model_catalog_logcenter->getLogcenterByUserId($this->user->getId());
          $comment = '采购单商品已全部收到';
          //$this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), $logcenter_info['logcenter_name'], $comment);
          $this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), $this->user->getUserName(), $comment);
        }

        //强制置为入库记录为待审核
        $this->model_sale_purchase_order->changePoStatus($id, 7);

      }

      $this->response->setOutput(json_encode(array('success'=>'生成入库单成功')));
      return;
    }
  }

  public function delete() {
    $json = array();

    $this->load->model('sale/purchase_order');

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }

    $po = $this->model_sale_purchase_order->getPo($id);
    if(!$po||$po['status']!=0) {
      $json['error'] = '非新增状态采购单不能删除';
    }
    else {
      $this->model_sale_purchase_order->deletePo($id);
      $json['success'] = '删除成功';
    }

    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
  }

  public function batch() {
    $json = array();

    $this->load->model('sale/purchase_order');
    foreach($this->request->post['selected'] as $id){

	    $po = $this->model_sale_purchase_order->getPo($id);
	    if(!$po||$po['status']!=0) {
	      //$json['error'] = '非新增状态采购单不能删除';
		}else {
	      $this->model_sale_purchase_order->deletePo($id);
	      //$json['success'] = '删除成功';
	    }
    }
    /*
    if (isset($this->request->server['HTTP_ORIGIN'])) {
      $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
      $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      $this->response->addHeader('Access-Control-Max-Age: 1000');
      $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
    }

    $this->response->addHeader('Content-Type: application/json');
    $this->response->setOutput(json_encode($json));
    */

    $this->getList();

  }

  protected function form(){
        $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

    $data['token'] = $this->session->data['token'];

    $id = I('get.po_id');
    if(!$id){
      $id=0;
    }


    if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    $po = $this->model_sale_purchase_order->getPo($id);
    $warehouse = $this->model_sale_purchase_order->getWarehouse();
    $data['po'] = $po;
    $data['warehouse'] = $warehouse;
    $po_products = $this->model_sale_purchase_order->getPoProducts($id);
    $data['po_products'] = $po_products;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/purchase_order.tpl', $data));
  }



  protected function getList() {
    $page = I('get.page');
    if(!$page){
      $page = 1;
    }
    if($this->user->getLp()){
        //$filter['po.user_id'] = $this->user->getId();
    }
    else if($this->user->getVp()){
        $filter['po.vendor_id'] = $this->user->getId();
    }
    $data = I('get.');

    if(!empty($data['filter_date_start'])){
      $filter_date_start = $data['filter_date_start'];
    }else{
      $filter_date_start = '0000-00-00';
    }

    if(!empty($data['filter_date_end'])){
      $filter_date_end = $data['filter_date_end'];
    }else{
      $filter_date_end = '9999-12-31';
    }

    $filter['po.date_added'] = array('between',array($filter_date_start,$filter_date_end));
    if(!empty($data['filter_vendor_name'])){
      $filter_vendor_name = trim($data['filter_vendor_name']);
      $filter['v.vendor_name'] = array('like',"%".$filter_vendor_name."%");
    }

    if(!empty($data['filter_logcenter'])){
      $filter_logcenter = trim($data['filter_logcenter']);
      $filter['lg.logcenter_name'] = array('like',"%".$filter_logcenter."%");
    }

    if(!empty($data['filter_sku'])){
      $filter_sku = trim($data['filter_sku']);
      $pos_id_array = $this->model_sale_purchase_order->getPoIdsBySku($filter_sku);
      if(!$pos_id_array){
        $pos_id_array = array('0');
      }

      $filter['po.id'] = array('in',$pos_id_array);

    }

    if(isset($data['filter_status'])){
      $filter_status = trim($data['filter_status']);
      if($filter_status!='*'){
        $filter['po.status'] = $filter_status;
      }
    }else{
      $data['filter_status'] = '*';
    }

    /*
     * 强制添加仓库筛选功能
     * @author sonicsjh
     */
    $data['warehouseLocked'] = false;
    if ($this->user->getLP() > 0) {
        $data['warehouseLocked'] = true;
        $filter['warehouse_id'] = $this->user->getLP();
        unset($filter['lg.logcenter_name']);
    }

    $po_list =  $this->model_sale_purchase_order->getList($page, $filter);
    foreach ($po_list as $key => $value) {
      $po_list[$key]['all_color'] = $this->model_sale_purchase_order->checkPoOrderDate($value['date_added'],$value['status']);
    }
    $order_total = $this->model_sale_purchase_order->getListCount($filter);

    $pagination = new Pagination();
    $pagination->total = $order_total;
    $pagination->page = $page;
    $pagination->limit = $this->config->get('config_limit_admin');
    $pagination->url = $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] . '&page={page}&filter_date_start='.$data['filter_date_start'].'&filter_date_end='.$data['filter_date_end'].'&filter_logcenter='.$data['filter_logcenter'].'&filter_status='.$data['filter_status'].'&filter_vendor_name='.$data['filter_vendor_name'].'&filter_sku='.$data['filter_sku'], 'SSL');
    $data['status_array'] = getPoStatus();
    $data['status_array']['*'] = '全部';

    $data['pagination'] = $pagination->render();

    $data['breadcrumbs'] = array();

    $data['breadcrumbs'][] = array(
      'text' => $this->language->get('text_home'),
      'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
    );

    $data['breadcrumbs'][] = array(
      'text' => '采购单',
      'href' => $this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'] , 'SSL')
    );

  $data['delete'] = $this->url->link('sale/purchase_order/batch', 'token=' . $this->session->data['token'] , 'SSL');
	$data['buyer'] = $this->url->link('sale/purchase_order/buyer', 'token=' . $this->session->data['token'] , 'SSL');

	if (isset($this->session->data['error'])) {
      $data['error_warning'] = $this->session->data['error'];

      unset($this->session->data['error']);
    } elseif (isset($this->error['warning'])) {
      $data['error_warning'] = $this->error['warning'];
    } else {
      $data['error_warning'] = '';
    }

    if (isset($this->session->data['success'])) {
      $data['success'] = $this->session->data['success'];

      unset($this->session->data['success']);
    } else {
      $data['success'] = '';
    }

    //是否可以生成采购单
    $data['can_add_po'] = $this->user->getLPLevel() == 1;
    $data['can_add_po'] = 1;

    $data['token'] = $this->session->data['token'];

    $data['po_list'] = $po_list;

    $data['header'] = $this->load->controller('common/header');
    $data['column_left'] = $this->load->controller('common/column_left');
    $data['footer'] = $this->load->controller('common/footer');

    $this->response->setOutput($this->load->view('sale/purchase_order_list.tpl', $data));
  }

  public function allowStock(){
    if ($this->request->server['REQUEST_METHOD'] == 'POST') {
      $this->load->model('sale/purchase_order');
      $data = json_decode(file_get_contents('php://input'), true);
      $filter = C('DEFAULT_FILTER');
      $data   =   is_array($data) ? array_map_recursive($filter,$data) : $filter($data);

      // $id = I('post.po_id');
      $id = $data['po_id'];
      if(!$id){
        $id=0;
      }
      $po = $this->model_sale_purchase_order->getPo($id);
      //判断po状态，如果是已经结算或者已经关闭，则不允许修改po数量
      if($po['status'] == 5 || $po['status'] == 9) {
        $this->response->setOutput(json_encode(array('error'=>'不能修改已结算和已关闭采购单')));
        return;
      }

      //判断库存是否全部匹配，如果是的话，就置为全部收货，否则置为部分收货
      $po_products = $this->model_sale_purchase_order->getPoProducts($id);
      $delivered_qty_total = 0;
      $fully_delivered = true;
      $po_status = 0;
      foreach ($po_products as $po_p) {
        $delivered_qty_total += $po_p['delivered_qty'];
        if($po_p['qty'] != $po_p['delivered_qty']) {
          $fully_delivered = false;
        }
      }
      if($fully_delivered) {
        $po_status = 4;
      } elseif($delivered_qty_total!=0) {
        $po_status = 3;
      }
      if($po_status != 0) {
        $this->model_sale_purchase_order->changePoStatus($id, $po_status);
        //入库批准
        if(1) {
          $this->load->model('catalog/logcenter');
          $comment = '批准入库记录';
          $this->model_sale_purchase_order->addPoHistory($id, $this->user->getId(), '物流管理员 '.$this->user->getUserName(), $comment);
        }
      }

      $this->response->setOutput(json_encode(array('success'=>'成功批准入库记录')));
      return;
    }
  }

  public function addProductInitiai($data){
      $this->load->model('sale/purchase_order');
      $this->model_sale_purchase_order->addProductInitiai($data);
  }
  public function addmulti(){
      $this->load->model('sale/purchase_order');
      $this->model_sale_purchase_order->addmulti($this->user->getId());
      // $this->getList();
  }

    /*
     * 一键创建采购单
     * @author sonicsjh
     */
    public function autoPurchaseOrder() {
        $this->load->model('stock/warehouse');
        $list = $this->model_stock_warehouse->getAvailableWarehouse();
        foreach ($list as $info) {
            $availableWarehouseList[$info['warehouse_id']] = $info['can_recive'];
        }

        $this->load->model('stock/stocksearch');
        $inventoryProducts = $this->model_stock_stocksearch->getProductsLTsafeQty($availableWarehouseList, array());//安全库存缺货

        $this->load->model('sale/order');
        $inventoryProducts = $this->model_sale_order->getProductsWithLackQtyGTZero($availableWarehouseList, $inventoryProducts);//单品缺货
        $inventoryProducts = $this->model_sale_order->getGroupProductsWithLackQtyGTZero($availableWarehouseList, $inventoryProducts);//组合销售缺货

        $inventoryProducts = $this->_initProductInfo($inventoryProducts);//格式化缺货数据

        $ret = $this->_purchaseOrderHistoryCheck($inventoryProducts);//历史采购单和新增缺货采购比对，有的加商品或者改数量，没有的新增采购单

        $this->session->data['success'] = '修改了 <strong>'.$ret['modify']['po'].'</strong> 个采购单，包含 <strong>'.$ret['modify']['popM'].'</strong> 个商品修改，<strong>'.$ret['modify']['popN'].'</strong> 个商品新增。<br />创建了 <strong>'.$ret['new']['po'].'</strong> 个采购单，包含 <strong>'.$ret['new']['pop'].'</strong> 个商品。';
        //一键采购由弓飞操作，暂时跳转回 main_purchase_order
        //$this->response->redirect($this->url->link('sale/purchase_order', 'token=' . $this->session->data['token'], 'SSL'));
        $this->response->redirect($this->url->link('sale/main_purchase_order', 'token=' . $this->session->data['token'], 'SSL'));
    }

    /*
     * 格式化缺货数据，便于和历史采购单比对
     * array(
     *   warehouseId_vendorId => array(
     *     采购主表信息,
     *     products => array(
     *       pCode => 商品信息,
     *       pCode => 商品信息,
     *     ),
     *   ),
     * )
     * @author sonicsjh
     */
    protected function _initProductInfo($inventoryProducts) {
        $purchaseOrderList = array();
        $this->load->model('catalog/mvd_product');
        $this->load->model('user/user');
        foreach ($inventoryProducts as $warehouseId=>$v) {
            $warehouseUserId = $this->model_user_user->getUserIdByWarehouseId($warehouseId);
            foreach ($v as $productCode=>$vv) {
                $productInfo = $this->model_catalog_mvd_product->getInfoIntoPoProductByProductCode($productCode);
                if (intval($productInfo['vUserId']) < 1) {
                    unset($inventoryProducts[$warehouseId][$productCode]);
                    continue;
                }
                $k = $warehouseId.'_'.$productInfo['vUserId'];
                if (!array_key_exists($k, $purchaseOrderList)) {
                    $purchaseOrderList[$k] = array(
                        'user_id' => $warehouseUserId['user_id'],
                        'date_added' => date('Y-m-d H:i:s'),
                        'status' => '0',
                        'vendor_id' => $productInfo['vUserId'],
                        'total' => 0,
                        'included_order_ids' => '',
                        'warehouse_id' => $warehouseId,
                    );
                }
                /* 按整件数计算最少采购量 */
                $packingNo = max(1, intval($productInfo['productPackingNo']));
                $qty = ceil($vv['nums'] / $packingNo) * $packingNo;
                /* 按整件数计算最少采购量 */
                $purchaseOrderList[$k]['products'][$productCode] = array(
                    'product_id' => $productInfo['productId'],
                    'qty' => $qty,
                    'unit_price' => $productInfo['productCost'],
                    'price' => $productInfo['productCost']*$qty,
                    'status' => '0',
                    'name' => $productInfo['productName'],
                    'sku' => $productInfo['productSku'],
                    'comment' => '',
                    'sort_order' => '0',
                    'option_id' => $productInfo['productOptionId'],
                    'option_name' => $productInfo['productOptionName'],
                    'packing_no' => $productInfo['productPackingNo'],
                    'product_code' => $productCode,
                );
                $purchaseOrderList[$k]['total'] += $productInfo['productCost']*$vv['nums'];
                if ('' != $vv['orderIds']) {
                    $purchaseOrderList[$k]['included_order_ids'] .= ','.$vv['orderIds'];
                }
            }
        }
        return $purchaseOrderList;
    }

    /*
     * 判断历史采购单中是否有缺货商品数据，有就更新历史采购单，移除缺货商品；返回未移除的缺货商品
     * @author sonicsjh
     */
    protected function _purchaseOrderHistoryCheck($inventoryProducts) {
        $ret['modify'] = array(
            'po' => 0,
            'popM' => 0,
            'popN' => 0,
        );
        $this->load->model('catalog/logcenter');
        //$logcenterInfo = $this->model_catalog_logcenter->getLogcenterByUserId($this->user->getId());
        $this->load->model('sale/purchase_order');
        $purchaseOrderHistory = $this->model_sale_purchase_order->getNewStatusPos();
/*
echo "POH\n\r\n\r";
print_r($purchaseOrderHistory);
echo "\n\rIP\n\r\n\r";
print_r($inventoryProducts);
exit();
*/
        foreach ($purchaseOrderHistory as $key=>$v) {//调整历史采购单
            if (is_array($inventoryProducts[$key])) {
                $total = 0;
                $comment = '修改商品数量：<br />';
                $poId = $v['PO_PK'];
                $includedOrderIds = $v['includedOrderIds'];
                foreach ($v['products'] as $productCode=>$pv) {
                    if (is_array($inventoryProducts[$key]['products'][$productCode])) {//缺货商品存在于历史采购单中
                        /* 按整件数计算最少采购量 */
                        $packingNo = max(1, intval($inventoryProducts[$key]['products'][$productCode]['packing_no']));
                        $newQty = max($pv['qty'], $inventoryProducts[$key]['products'][$productCode]['qty']);
                        $newQty = ceil($newQty/$packingNo) * $packingNo;
                        /* 按整件数计算最少采购量 */
                        if ($newQty != $pv['qty']) {//更新采购数量
                            $this->model_sale_purchase_order->updateQtyByPoProductId($pv['POP_PK'], $newQty, $inventoryProducts[$key]['products'][$productCode]['unit_price'], $inventoryProducts[$key]['products'][$productCode]['packing_no']);
                            $comment .= '商品编码：'.$productCode.',商品数量：'.$pv['qty'].' 到 '.$newQty.'<br />';
                            $includedOrderIds .= '';
                            $ret['modify']['popM']++;
                        }
                        $total += $newQty * $inventoryProducts[$key]['products'][$productCode]['unit_price'];
                        unset($inventoryProducts[$key]['products'][$productCode]);//移除单品
                    }else{
                        $total += $pv['tPrice'];
                    }
                }
                if ('修改商品数量：<br />' == $comment) {
                    $comment = '新增商品：<br />';
                    foreach ($inventoryProducts[$key]['products'] as $productCode=>$poProductInfo) {
                        $this->model_sale_purchase_order->addPoProductInfo($poId, $poProductInfo);
                        $comment .= '商品编码：'.$productCode.',商品数量：'.$poProductInfo['qty'].'<br />';
                        $includedOrderIds .= '';
                        $ret['modify']['popN']++;
                        $total += $inventoryProducts[$key]['products'][$productCode]['qty'] * $inventoryProducts[$key]['products'][$productCode]['unit_price'];
                    }
                }
                if ('新增商品：<br />' != $comment) {//修改po主表信息，创建日志信息
                    $data = array(
                        'total' => $total,
                        'included_order_ids' => $includedOrderIds,
                    );
                    $this->model_sale_purchase_order->updatePoByPK($poId, $data);
                    $this->model_sale_purchase_order->addPoHistory($poId, $this->user->getId(), $this->user->getUserName(), $comment);
                    $ret['modify']['po']++;
                }
                unset($inventoryProducts[$key]);
            }
        }
        $ret['new'] = $this->model_sale_purchase_order->addPos($inventoryProducts);
        return $ret;
    }

    public function buyer(){
        $this->document->setTitle('采购单');

        $this->load->model('sale/purchase_order');

      if(isset($this->request->post['selected'])){
        foreach($this->request->post['selected'] as $po_id){
          $podata = $this->model_sale_purchase_order->getPoStatusById($po_id);
          if ('0'===$podata['status']) {
            $this->model_sale_purchase_order->addInQty($podata);

          }

        }
      }


      $this->getList();
    }
}
